import json
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

from .serializers import BookSerializers
from .models import BookInfo
# Create your views here.


class BookView(View):
    def get(self, request, pk):
        # 序列化的时候要将模型类对象传递给instance参数，反序列化的时候要将被反序列化的数据传递给data参数
        # # 查询书籍方法一:
        # book = BookInfo.objects.get(id=pk)
        # ser = BookSerializers(book)  # 将模型类对象传递给instance，不需要考虑序列化器定义时的required=True的参数

        # 查询书籍方法二:
        book = BookInfo.objects.get(id=pk)
        # 因为序列化器定义时候id和name字段是被要求的必须的，所以被反序列化的数据至少包含这两个参数
        # 返回的结果也只包含data指明的字段
        data = {'id': book.id, 'name': book.name, 'readcount': book.readcount, 'commentcounts': book.commentcount}
        ser = BookSerializers(data=data)
        ser.is_valid(raise_exception=True)  # raise_exception置为True时，当缺少参数是直接抛出异常
        print(ser.errors)
        print(ser.validated_data)
        print(ser.data)

        # ser.data 是序列化

        return JsonResponse(ser.data)

    def put(self, request, pk):
        """
        更新图书
        :param request:
        :param pk:
        :return:
        """
        book = BookInfo.objects.get(id=pk)
        name = json.loads(request.body.decode()).get('name')
        data = {'name': name}

        ser = BookSerializers(instance=book, data=data)
        ser.is_valid()
        # print(ser.errors)  # 查看验证结果，成功返回空字典，失败返回错误信息
        ser.save()
        print(ser.validated_data)

        return JsonResponse(ser.data, json_dumps_params={'ensure_ascii': False})


class BooksView(View):
    def get(self, request):
        book = BookInfo.objects.all()
        ser = BookSerializers(book, many=True)

        return JsonResponse(ser.data, safe=False)

    def post(self, request):
        """
        增加图书
        :param request:
        :return:
        """
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')
        pub_date = json_dict.get('pub_date')
        readcount = json_dict.get('readcount')
        commentcounts = json_dict.get('commentcounts')
        is_delete = json_dict.get('is_delete')
        data = {  # data和序列化器类中的字段名称必须和模型类中定义的名称一样
            'name': name,
            'pub_date': pub_date,
            'readcount': readcount if readcount else 0,
            'commentcount': commentcounts if commentcounts else 0
            # 'is_delete': is_delete
        }
        ser = BookSerializers(data=data)
        ser.is_valid(raise_exception=True)
        book = ser.save()  # 序列化器中不传入instance时调用save方法调用的就是create，新增数据的方法

        return JsonResponse(ser.data)

